from datetime import datetime, timedelta

from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
import time

from info import constants, db
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import admin_blu


@admin_blu.route('/login', methods=['get', 'post'])
@user_login_data
def login():
    if request.method == 'GET':
        user = g.user
        if user and user.is_admin:
            return redirect(url_for('admin.index'))

        return render_template('admin/login.html')

    # 获取表单的参数

    username = request.form.get('username')
    password = request.form.get('password')

    if not all([username, password]):
        return render_template('admin/login.html', errmsg="参数不足")

    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as ret:
        current_app.logger.error(ret)
        return render_template('admin/login.html', errmsg="数据查询失败")

    if not user:
        return render_template('admin/login.html', errmsg="用户不存在")

    if not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg="账户或密码不存在")

    session['user_id'] = user.id

    return redirect(url_for('admin.index'))


@admin_blu.route('/index')
@user_login_data
def index():
    user = g.user
    if user and user.is_admin:
        data = {
            'user': user.to_dict()
        }
        return render_template('admin/index.html', data=data)

    return redirect('/')


@admin_blu.route('/news_edit')
def news_edit():
    page = request.args.get('page', 1)
    keywords = request.args.get('keywords', None)
    print(request.url, keywords)
    try:
        page = int(page)
    except Exception as ret:
        current_app.logger.error(ret)
        page = 1

    filters = []
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time). \
            paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as ret:
        current_app.logger.error(ret)
        current_page = 1
        total_page = 1
        news_list = []

    news_list = [new.to_basic_dict() for new in news_list]
    data = {
        'current_page': current_page,
        'total_page': total_page,
        'news_list': news_list,
        'keywords': keywords
    }
    return render_template('admin/news_edit.html', data=data)


@admin_blu.route('/news_edit_detail', methods=['get', 'post'])
def news_edit_detail():
    if request.method == 'GET':
        news_id = request.args.get('news_id')
        news = News.query.get(news_id)
        categories = Category.query.filter(Category.id != 1).all()
        categories = [category.to_dict() for category in categories]
        data = {
            'news': news.to_dict(),
            'categories': categories
        }
        return render_template('admin/news_edit_detail.html', data=data)

    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    if not all([title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")

    # 1.2 尝试读取图片
    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 2. 将标题图片上传到七牛
        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    # 3. 设置相关数据
    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    return jsonify(errno=RET.OK, errmsg="编辑成功")


@admin_blu.route('/news_review_detail/<int:news_id>', methods=['post', 'get'])
def news_review_detail(news_id):
    if request.method == 'GET':
        try:
            news = News.query.get(news_id)
        except Exception as ret:
            current_app.logger.error(ret)
            return render_template('admin/news_review_detail.html', errmsg='数据库查询错误')

        if not news:
            return render_template('admin/news_review_detail.html', errmsg='新闻不存在')

        data = {
            'news': news.to_dict()
        }
        return render_template('admin/news_review_detail.html', data=data)

    news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    try:
        news_id = int(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    try:
        news = News.query.get(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg='数据库查询错误')

    if not news:
        return jsonify(errno=RET.PARAMERR, errmsg='新闻不存在')
    if action not in ['accept', 'reject']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    if action == 'accept':
        news.status = 0
    else:
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
        news.status = -1
        news.reason = reason
    return jsonify(errno=RET.OK, errmsg='操作成功')


@admin_blu.route('/news_review')
def news_review():
    page = request.args.get('page', 1)
    keywords = request.args.get('keywords', None)

    try:
        page = int(page)
    except Exception as ret:
        current_app.logger.error(ret)
        page = 1

    filters = [News.status != 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time). \
            paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as ret:
        current_app.logger.error(ret)
        current_page = 1
        total_page = 1
        news = []

    news = [new.to_review_dict() for new in news]
    data = {
        'current_page': current_page,
        'total_page': total_page,
        'news_list': news,
        'keywords': keywords
    }

    return render_template('admin/news_review.html', data=data)


@admin_blu.route('/news_type', methods=['get', 'post'])
def news_type():
    if request.method == 'GET':
        categories = Category.query.filter(Category.id != 1).all()
        categories = [category.to_dict() for category in categories]
        data = {
            'categories': categories
        }
        return render_template('admin/news_type.html', data=data)

    category_id = request.json.get("id")
    category_name = request.json.get("name")

    if not category_name:
        return jsonify(errno=RET.DATAEXIST, errmsg='参数有误')

    if category_id:
        try:
            category = Category.query.get(category_id)
        except Exception as ret:
            current_app.logger.error(ret)
            return jsonify(errno=RET.DATAERR, errmsg='数据库错误')

        if not category:
            return jsonify(errno=RET.NODATA, errmsg='没有数据')

        category.name = category_name

    else:
        category = Category()
        category.id = category_id
        category.name = category_name
        db.session.add(category)

    return jsonify(errno=RET.OK, errmsg='操作成功')


@admin_blu.route('/user_count')
@user_login_data
def user_count():
    #  查询数据
    #  用户总数
    all_users = 0
    try:
        all_users = User.query.filter(User.is_admin == False).count()
    except Exception as ret:
        current_app.logger.error(ret)

    # 用户月曾数
    now_moth = time.strftime('%Y-%m-01', time.localtime())
    moth = datetime.strptime(now_moth, '%Y-%m-%d')
    month_users = 0
    try:
        month_users = User.query.filter(User.is_admin == False, User.create_time > moth).count()
    except Exception as ret:
        current_app.logger.error(ret)

    # 用户日曾数
    now_day = time.strftime('%Y-%m-%d', time.localtime())
    day = datetime.strptime(now_day, '%Y-%m-%d')
    day_users = 0
    try:
        day_users = User.query.filter(User.is_admin == False, User.create_time > day).count()
    except Exception as ret:
        current_app.logger.error(ret)

    #  用户活跃曲线图
    active_time = []
    active_count = []
    for i in range(30):
        begin_data = day - timedelta(days=i)
        end_time = day - timedelta(days=(i-1))
        count = User.query.filter(User.is_admin == False,
                                  end_time >= User.last_login, User.last_login > begin_data).count()
        active_count.append(count)
        active_time.append(begin_data.strftime('%Y-%m-%d'))
    active_time.reverse()
    active_count.reverse()
    print(active_time)
    print(active_count)
    data = {
        'all_users': all_users,
        'month_users': month_users,
        'day_users': day_users,
        'active_time': active_time,
        'active_count': active_count
    }
    return render_template('admin/user_count.html', data=data)


@admin_blu.route('/user_list')
def user_list():
    page = request.args.get('page', 1)

    try:
        page = int(page)
    except Exception as ret:
        current_app.logger.error(ret)
        page = 1

    users = None
    paginate = []
    current_page = 1
    total_page = 1
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login). \
            paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
    except Exception as ret:
        current_app.logger.error(ret)

    users = paginate.items
    current_page = paginate.page
    total_page = paginate.pages

    users = [user.to_admin_dict() for user in users]
    data = {
        'users': users,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('admin/user_list.html', data=data)
